import React from 'react';
import { formatMessage } from 'umi/locale';
import Link from 'umi/link';
import { connect } from 'dva';
import pathToRegexp from 'path-to-regexp';
import Exception from '@/components/Exception';
import Authorized from '@/utils/Authorized';

const getRouteAuthority = (path, routeData) => {
  let authorities;
  routeData.forEach(route => {
    // match prefix
    if (pathToRegexp(`${route.path}(.*)`).test(path)) {
      // exact match
      if (route.path === path) {
        authorities = route.authority || authorities;
      } // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || route.authority;
      }
    }
  });
  return authorities;
};

const AuthComponent = ({ children, route, location, user }) => {
  const { routes = [] } = route;
  if (user.currentUser && location.pathname !== '/center/mfa') {
    const { hasBindSecretKey } = user.currentUser;
    const { href: redirect } = window.location;
    if (!hasBindSecretKey) {
      setTimeout(() => {
        window.location.replace(`/#/center/mfa?redirect=${redirect}`);
      }, 0);
    }
  }

  return (
    <Authorized
      authority={getRouteAuthority(location.pathname, routes) || ''}
      noMatch={
        <Exception
          type="403"
          desc={formatMessage({ id: 'app.exception.description.403' })}
          linkElement={Link}
          backText={formatMessage({ id: 'app.exception.back' })}
        />
      }
    >
      {children}
    </Authorized>
  );
};
export default connect(({ user, login }) => ({
  user,
  login,
}))(AuthComponent);
